package com.navinfo.platform.trip.common.arithmetic;

import com.navinfo.platform.trip.common.arithmetic.annotation.Arithmetic;
import com.navinfo.platform.trip.common.arithmetic.data.CommonData;
import com.navinfo.platform.trip.common.arithmetic.data.OuterStatisticData;
import com.navinfo.platform.trip.common.arithmetic.var.VarGasSteady;
import com.navinfo.platform.trip.common.arithmetic.exception.RangeAssert;
import com.navinfo.platform.trip.common.arithmetic.manager.AbstractArithmetic;
import com.navinfo.platform.trip.common.config.ConfigMap;
import com.navinfo.platform.trip.common.util.ArithmeticUtils;

/**
 * 稳定油门算法<br>
 * 输出：统计<br>
 */
@Arithmetic(name = "稳定油门算法")
public class GasSteady extends AbstractArithmetic<VarGasSteady> {
    /**
     * 稳定波动阀值，单位%
     */
    private static int stableInterval = ConfigMap.getInteger("SteadyAccelerator_StableInterval_Threshold");
    /**
     * 速度限制 单位:km/h
     */
    private static double speedThreshold = ConfigMap.getInteger("SteadyAccelerator_Speed_Threshold");
    /**
     * 累计时长，单位ms
     */
    private static int timeThreshold = ConfigMap.getInteger("SteadyAccelerator_Times_Threshold");

    @Override
    public void calculate() {
        logger.debug("@进入稳定油门算法.");
        VarGasSteady var = getObj();
        CommonData commonData = getCommonData();

        //1.油门开合度有效性判断
        double accelerator = commonData.getAcceleratorPosition();
        RangeAssert.acceleratorIsInTheRange(accelerator);

        //引入车速作为辅助判断条件；当车速>5KM/H时，油门开度稳定在某一个区域(+-3%)并延续30秒，则该区域一次计数。
        //油门开度为0时也作为判断依据
        if (!commonData.isTripFirstNode()) {
                double acceleratorDiff = Math.abs(accelerator - var.getPerAccelerator());
                if (acceleratorDiff<=stableInterval && commonData.getSpeedKmh() > speedThreshold) {
                    var.setCacheTimeMsInOneMinutes(var.getCacheTimeMsInOneMinutes() + commonData.getDffTime());
                } else {
                    if (var.getCacheTimeMsInOneMinutes() >= timeThreshold) {
                        var.setTimeMs(var.getTimeMs() + var.getCacheTimeMsInOneMinutes());
                        var.setNumber(var.getNumber() + 1);
                    }
                    var.setCacheTimeMsInOneMinutes(0);
                    var.setPerAccelerator(accelerator);
                }
        }else {
            //更新油门开度供下次使用
            var.setPerAccelerator(accelerator);
        }

        logger.debug("@稳定油门算法结束.");
    }

    @Override
    public void collect(OuterStatisticData statisticDataOut) {
        VarGasSteady var = super.getObj();
        statisticDataOut.setGasStabilityNumber(var.getNumber());
        statisticDataOut.setGasStabilityDuration(ArithmeticUtils.timeMsToSecond(var.getTimeMs()));
    }
}
